package com.homework.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.homework.dto.AdminLoginDTO;
import com.homework.dto.Result;
import com.homework.entity.Admin;
import com.homework.mapper.AdminMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Slf4j
@Service
public class AuthService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 管理员登录
     */
    public Result<String> login(AdminLoginDTO loginDTO, HttpSession session) {
        log.info("开始登录验证 - 用户名: {}", loginDTO.getUsername());
        log.debug("原始密码: [{}]", loginDTO.getPassword());

        // 查询管理员信息
        Admin admin = adminMapper.selectOne(
            new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, loginDTO.getUsername())
        );

        log.debug("数据库查询结果: {}", admin);

        if (admin == null) {
            log.warn("用户不存在 - 用户名: {}", loginDTO.getUsername());
            return Result.error("用户名或密码错误");
        }

        log.debug("数据库中存储的密码哈希: {}", admin.getPassword());
        log.debug("用户salt: {}", admin.getSalt());

        // 验证密码
        boolean passwordMatch = passwordEncoder.matches(loginDTO.getPassword(), admin.getPassword());
        log.debug("密码验证结果: {}", passwordMatch);

        if (!passwordMatch) {
            log.warn("密码验证失败 - 用户名: {}", loginDTO.getUsername());
            return Result.error("用户名或密码错误");
        }

        // 将管理员信息存入session
        String token = UUID.randomUUID().toString();
        session.setAttribute("admin", admin);
        session.setAttribute("token", token);

        log.info("登录成功 - 用户名: {}, Token: {}", loginDTO.getUsername(), token);
        return Result.success("登录成功");
    }

    /**
     * 管理员登出
     */
    public Result<String> logout(HttpSession session) {
        session.removeAttribute("admin");
        session.removeAttribute("token");
        return Result.success("登出成功");
    }

    /**
     * 检查登录状态
     */
    public Result<Boolean> checkLoginStatus(HttpSession session) {
        Boolean isLogin = session.getAttribute("admin") != null;
        return Result.success(isLogin);
    }
}